package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.model.Goods;
import com.qf.model.GoodsType;
import com.qf.service.GoodService;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.util.PageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@WebServlet("/goods")
public class GoodController extends BaseServlet{
    GoodService service=new GoodsServiceImpl();
    //获取所有的商品分类
    public String goodsType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<GoodsType> typeList = service.getTypeList();
        String s = JSON.toJSONString(typeList);
       return s;
    }


    public String getGoods (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer tid=Integer.parseInt(request.getParameter("typeid"));
        String pname="";
        String pname1 = request.getParameter("pname");
        if(pname1!=null){
            pname=pname1;
        }
        PageBean<Goods> pageBean=new PageBean<>();
        //每页展示四条记录
        pageBean.setPageSize(4);
        String nowPage = request.getParameter("pageIndex");
        if(nowPage!=null){
            pageBean.setPageIndex(Integer.parseInt(nowPage));
        }

        //最大记录数
       // select count(*) from product where tid=? and pname like ?
        int totalCount=service.getCount(tid,pname);
        pageBean.setTotalCount(totalCount);
        int pageMax=(totalCount+pageBean.getPageSize()-1)/pageBean.getPageSize();
        pageBean.setPageMax(pageMax);

        List<Goods> list=service.getGoods(pageBean,tid,pname);
        pageBean.setList(list);
        request.setAttribute("pageBean",pageBean);
        request.setAttribute("tid",tid);
        request.setAttribute("pname",pname);

        return "FORWARD:goodsList.jsp";
    }


    public String getGoodsDetail (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String idStr = request.getParameter("id");
        //select * from product where pid=?
        Goods good=service.getGood(Integer.parseInt(idStr));

        request.setAttribute("good",good);
        return "FORWARD:goodsDetail.jsp";
    }
}
